<template>
  <div class="my-center">
    <div class="info">
      <!-- 用户基本信息修改按钮 -->
      <div class="content-left">
        <!-- 展示当前的用户的头像 -->
        <div class="avatar">
          <el-avatar :size="245" shape="square" :src="avatar"></el-avatar>
        </div>
        <div class="function-button">
          <ul>
            <!-- 修改头像 -->
            <li>
              <el-upload name="part" :action="action" :multiple="false"
                         :data="{token}"
                         :before-upload="beforeAvatarUpload"
                         :on-success="handleAvatarSuccess"
                         :show-file-list="false">
                <el-button> <i class="el-icon-upload2"></i> 修改头像</el-button>
              </el-upload>
            </li>
            <li> <el-button @click="alterName"> <i class="el-icon-edit-outline"></i> 修改昵称</el-button></li>

            <!-- 修改签名 -->
            <li>
              <el-button @click="signatureDialog=true" > <i class="el-icon-s-flag"></i> 修改签名</el-button>
              <!-- 修改签名的弹窗 -->
              <el-dialog title="修改签名" :visible.sync="signatureDialog">
                <el-input v-model="newSignature" maxlength="220"
                          :autosize="{ minRows: 6}"
                          show-word-limit resize="none"
                          type="textarea" placeholder="请输入内容"></el-input>
                <el-button @click="signatureDialog = false">取 消</el-button>
                <el-button type="primary" :disabled="disabledSignature" @click="alterSignature">提交</el-button>
              </el-dialog>
            </li>

            <!-- 修改密码按钮-->
            <li>
              <el-button @click="outerVisible = true"><i class="el-icon-edit"></i> 修改密码</el-button>
              <!-- 修改密码的弹窗 -->
              <el-dialog title="提示" :visible.sync="outerVisible">
                <el-form :rules="rules" :model="check" @submit.native.prevent>
                  <el-form-item label="输入密码验证：" prop="password" label-width="130px">
                    <el-input v-model="check.password" show-password></el-input>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="outerVisible = false">取 消</el-button>
                  <el-button type="primary" @click="alterPassword">确 定</el-button>
                </div>
              </el-dialog>
              <!-- 获取用户输入的密码 -->
              <el-dialog title="提示" :visible.sync="passwordVisible">
                <el-form :rules="rules" :model="newPass">
                  <el-form-item label="输入新密码：" prop="password" label-width="130px">
                    <el-input v-model="newPass.password" show-password></el-input>
                  </el-form-item>
                  <el-form-item label="确认新密码：" prop="checkPass" label-width="130px">
                    <el-input v-model="newPass.checkPass" show-password></el-input>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="passwordVisible = false">取 消</el-button>
                  <el-button type="primary" @click="submitPassword">确 定</el-button>
                </div>
              </el-dialog>
            </li>

            <!-- 修改电话 -->
            <li>
              <el-button @click="alterPhone" ><i class="el-icon-edit-outline"></i> 修改电话</el-button>
            </li>
            <!-- 修改性别 -->
            <li>
              <el-button @click="sexDialog = true"><i class="el-icon-edit-outline"></i> 修改性别 </el-button>
              <el-dialog title="修改性别" :visible.sync="sexDialog">
                <el-radio v-model="newSex" :label="1">男</el-radio>
                <el-radio v-model="newSex" :label="2">女</el-radio>
                <el-radio v-model="newSex" :label="0">保密</el-radio>
                <div>
                  <el-button @click="sexDialog = false">取 消</el-button>
                  <el-button type="primary" :disabled="disabledSex" @click="alterSex">提交</el-button>
                </div>
              </el-dialog>
            </li>
          </ul>
        </div>
      </div>

      <!-- 用户基本信息展示 -->
      <div class="content-right">
        <div class="user-name">
          <h2>{{name}}</h2>
          <span>User Name</span>
        </div>
        <div class="user-info">
          <table>
            <tr>
              <td>昵称：</td>
              <td>{{name}}</td>
            </tr>
            <tr>
              <td>账号：</td>
              <td>{{id}}</td>
            </tr>
            <tr>
              <td>电话：</td>
              <td>{{phone}}</td>
            </tr>
            <tr>
              <td>性别：</td>
              <td>{{sex}}</td>
            </tr>
          </table>
          <div>
            签名：
            <span>{{signature}}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import {modifyName,modifySignature,modifyPhone,modifySex,verifyUser,modifyPass} from "@/api/user";
  import {validUserPass} from "@/utils/validate";
  export default {
        name: "PersonalCenter",
      computed:{
          ...mapGetters([
            'id','name','avatar','signature','sex','phone','token'
          ]),
        // 修改签名提交按钮是否禁用
        disabledSignature(){
            return  this.newSignature.trim() === ''
        },
        disabledSex(){
            return this.newSex === ''
        }
      },
      data(){
        // 校验用户输入密码合法性
        let validPassword = (rule, value, callback) => {
          console.log(value)
          if (value === '') {
            callback(new Error('请输入密码'));
          } else if (validUserPass(value)) {
            callback()
          }else{
            callback(new Error('密码输入不合法!'));
          }
        }
        // 校验再次输入密码的合法性
        let validCheckPass = (rule,value,callback)=>{
          console.log(value)
          if(value === ''){
            callback(new Error("密码不能为空"))
          }else if (this.newPass.password !== value) {
            callback(new Error("两次输入密码不一致"));
          }else{
            callback()
          }
        }
          return{
            // 上传头像请求地址
            action:process.env.VUE_APP_BASE_API+"/user/upload",
            signatureDialog:false, //签名输入框展示
            newSignature:'',
            phoneDialog:false,  // 修改电话输入框展示
            sexDialog:false,
            newSex:'',
            outerVisible:false,
            passwordVisible:false,
            check:{
              password:''
            },
            newPass:{
              password:'',
              checkPass:''
            },
            // 制定校验规则
            rules: {
              password: { validator: validPassword, trigger: 'blur' },
              checkPass:{validator:validCheckPass,trigger:'blur'},
            }

          }
      },
      methods:{
          // 上传文件之前的钩子，参数为上传的文件，若返回false或者返回Promise且被reject，则停止上传
        beforeAvatarUpload(file){
          const isJPG = file.type === 'image/jpeg';
          const isLt2M = file.size / 1024 / 1024 < 2;
          if(!isJPG){
            this.$message.error('上传头像图片只能是 JPG 格式！')
          }
          if(!isLt2M){
            this.$message.error('上传头像图片大小不能超过 2MB！')
          }
          return isJPG && isLt2M;
        },
        // 上传头像完成后的回调函数
        handleAvatarSuccess(res){
          console.log(res)
          if(res.code === 2000){
            this.$store.commit('user/SET_AVATAR',res.content.avatar)
            this.$message.success('头像修改成功!')
          }
        },
        // 修改昵称
        alterName(){
          this.$prompt('请输入昵称', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^[0-9a-zA-Z\u4e00-\u9fa5_]{1,8}$/,
            inputErrorMessage: '昵称输入不合法'
          }).then(({value})=>{
            modifyName(value).then(res=>{
              if(res.code === 2000){
                this.$store.commit('user/SET_NAME', value);
                this.$message.success("昵称修改成功！")
              }
            })
          }).catch(()=>{
            this.$message.info("取消修改")
          })
        },
        // 修改签名
        alterSignature(){
          modifySignature(this.newSignature).then(res=>{
            if(res.code === 2000){
              this.$store.commit('user/SET_SIGNATURE',this.newSignature)
              this.$message.success("签名修改成功！");
            }
            this.newSignature = ''
            this.signatureDialog = false
          })
        },
        // 修改电话号码
        alterPhone(){
          this.$prompt('请输入电话号码', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /^1[3456789]\d{9}$/,
            inputErrorMessage: '电话号码不合法'
          }).then(({value})=>{
            modifyPhone(value).then(res=>{
              if(res.code === 2000){
                this.$store.commit("user/SET_PHONE", value);
                this.$message.success("电话号码修改成功！")
              }
            })
          }).catch(()=>{
            this.$message.info("取消修改")
          })
        },
        // 修改性别
        alterSex(){
          modifySex(this.newSex).then(res=>{
            if(res.code === 2000){
              this.$store.commit('user/SET_SEX',this.newSex)
              this.$message.success("性别修改成功！")
            }
            this.newSex = ''
            this.sexDialog = false
          })
        },
        // 修改密码
        alterPassword(){
          let user = {
            userid:this.id,
            password:this.check.password
          }
          verifyUser(user).then(res=>{
            if(res.content.result){
              this.$message.success("验证密码正确！")
              this.passwordVisible = true // 显示下一个提示框
              this.outerVisible = false // 关闭当前提示窗
              return
            }
            this.$message.error("输入的密码不正确！")
          })

        },
        // 提交新密码
        submitPassword(){
          modifyPass(this.newPass.password).then(res=>{
            if(res.code === 2000){
              this.$message.success("密码修改成功！")
            }
            // 清空输入框
            this.newPass.password=''
            this.newPass.checkPass = ''
            this.check.password = ''
            this.passwordVisible = false // 弹窗消失
          })
        }
      }
    }
</script>

<style scoped>
  ul{
    padding: 0;
    margin: 0;
    list-style: none;
  }

  .my-center {
    height: 100%;
    overflow:hidden;
    background-image: linear-gradient(109.6deg, rgb(204, 228, 247) 11.2%, rgb(237, 246, 250) 100.2%);
  }
  .info{
    width: 640px;
    height: 495px;
    margin: 100px auto;
  }
  .my-center .content-left{
    float: left;
    height: 100%;
    width: 245px;
    text-align: center;
  }

  li>.el-button,
  .el-upload>.el-button {
    height: 41px;
    width: 245px;
    letter-spacing: 6px;
    font-size: 15px;
    border: 0;
    background-color: #cfe6f7;
    border-radius: 0;
  }

  .content-right {
    float: right;
    width: 395px;
    height: 100%;
  }
  .content-right .user-name{
    position: relative;
    height: 100px;
    width: 340px;
    border-bottom: 2px solid #c1bfbf;
    margin: 0 auto;
  }
  .content-right .user-name h2 {
    line-height: 80px;
    font-size: 28px;
    letter-spacing: 2px;
    color: #343d55;
  }
  .content-right .user-name span{
    position: absolute;
    bottom: 8px;
    font-size: 12px;
    font-family: Arial;
    letter-spacing: 1px;
    color: #a2a5a4;
  }

  .content-right .user-info{
    width: 340px;
    height: 100%;
    margin: 10px auto;
  }
  .content-right .user-info table{
    border-spacing: 10px 20px;
  }
  .content-right .user-info div{
    background-color: #dcdcef;
    padding: 10px;
    border-radius: 10px;
    margin-top: 10px;
  }
  .content-right .user-info span{
    letter-spacing: 1px;
    word-wrap: break-word;
  }

  .el-dialog .el-button {
    margin-top: 15px;
    margin-right: 20px;
    height: 30px;
    line-height: 5px;
  }
</style>
